package com.walkline.screen;

import net.rim.device.api.barcodelib.BarcodeBitmap;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.FullScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.google.zxing.WriterException;
import com.google.zxing.common.ByteMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;

public class QRCodeScreen extends FullScreen
{
	public QRCodeScreen()
	{
		super(new VerticalFieldManager(), Field.FOCUSABLE);
		QRCode qrCode = new QRCode();

		try
		{
			Encoder.encode(Integer.toHexString(DeviceInfo.getDeviceId()).toUpperCase(),ErrorCorrectionLevel.L, qrCode);
		} catch (WriterException e) {}

		int width = Display.getWidth();
		int height = Display.getHeight();
		int barSize = width >= height ? height : width;

		ByteMatrix barcode = qrCode.getMatrix();
		Bitmap bitmap = BarcodeBitmap.createBitmap(barcode,barSize);
		BitmapField bitmapField = new BitmapField(bitmap, LabelField.HCENTER | LabelField.VCENTER);

		add(bitmapField);
		//setStatus(new LabelField("PIN: " + Integer.toHexString(DeviceInfo.getDeviceId()).toUpperCase()));
	}

	protected boolean keyChar(char key, int status, int time)
	{
		onClose();
		return true;
	}
	
	protected boolean navigationClick( int status, int time ) 
    {
		onClose();
        return true;    
    }
	
	protected boolean trackwheelClick( int status, int time )
    {        
		onClose();    
        return true;
    }
	
	protected boolean touchEvent(TouchEvent message)
	{
		if(message.getEvent()==TouchEvent.UNCLICK)
		{
			onClose();
			return true;	
		}
		
		return super.touchEvent(message);
	}
	
	public boolean onClose()
	{
		UiApplication.getUiApplication().popScreen(this);
		return true;	
	}
}